package com.gun3y.test;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.gun3y.entity.Wrapper;
import com.gun3y.entity.media.PropertyType;
import com.gun3y.entity.pattern.AttributePattern;
import com.gun3y.entity.pattern.ExpressionType;
import com.gun3y.entity.pattern.FieldPattern;
import com.gun3y.entity.pattern.FieldType;
import com.gun3y.entity.pattern.PositionPattern;
import com.gun3y.entity.pattern.TagPattern;

public class WrapperUtils {

    public static String wrapperTo(Wrapper wrapper) {
	GsonBuilder builder = new GsonBuilder();
	Gson gson = builder.setPrettyPrinting().create();

	return gson.toJson(wrapper, Wrapper.class);
    }

    public static Wrapper wrapperFrom(String name) {
	InputStream resourceAsStream = WrapperUtils.class.getClassLoader().getResourceAsStream(name);
	InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream);
	Gson gson = new Gson();
	Wrapper wrapper = gson.fromJson(inputStreamReader, Wrapper.class);
	return wrapper;
    }

    public static Wrapper createWrapper() {
	Wrapper wrapper = new Wrapper();
	wrapper.setBase("http://www.imdb.com/");
	wrapper.setDescription("asd asd");
	wrapper.setName("imdb-movie");

	// //////// Field: Title //////////
	FieldPattern titlePattern = new FieldPattern();
	titlePattern.setFieldName(PropertyType.name);
	titlePattern.setMultipleResults(false);
	titlePattern.setFieldType(FieldType.Text);
	PositionPattern titlePositionPattern = new PositionPattern();
	titlePattern.setPosition(titlePositionPattern);

	TagPattern titleLocalTag = new TagPattern();
	titleLocalTag.setTagName("span");
	titleLocalTag.setTagExpression(ExpressionType.ExactMatch);

	AttributePattern at1 = new AttributePattern();
	at1.setAttributeName("class");
	at1.setAttributeValue("itemprop");
	at1.setAttributeExpression(ExpressionType.ExactMatch);

	AttributePattern at2 = new AttributePattern();
	at2.setAttributeName("itemprop");
	at2.setAttributeValue("name");
	at2.setAttributeExpression(ExpressionType.ExactMatch);

	titleLocalTag.setAttributes(Arrays.asList(at1, at2));
	titlePositionPattern.setLocalPattern(titleLocalTag);

	TagPattern titleParrent = new TagPattern();
	titleParrent.setTagName("h1");
	titleParrent.setTagExpression(ExpressionType.ExactMatch);

	AttributePattern at3 = new AttributePattern();
	at3.setAttributeName("class");
	at3.setAttributeValue("header");
	at3.setAttributeExpression(ExpressionType.ExactMatch);

	titleParrent.setAttributes(Arrays.asList(at3));
	titlePositionPattern.setParentPattern(titleParrent);

	wrapper.setFields(Arrays.asList(titlePattern));
	return wrapper;
    }

    public static void main(String[] args) {
	// Wrapper wrapper = WrapperUtils.createWrapper();
	System.out.println(WrapperUtils.wrapperTo(wrapperFrom("imdb.json")));
    }
}
